<template>
  <div class="layout-container" :class="currentTheme">
    <!-- 导航栏（公共部分） -->
    <nav class="navbar">
      <div class="brand" @click="navigateTo('/home')">
        <i class="fa fa-music"></i>
        <span>MelodyAI</span>
      </div>

      <!-- 导航按钮区域 -->
      <div class="nav-links">
        <!-- 创作大厅（下拉菜单） -->
        <div class="nav-dropdown" 
             @mouseenter="showCreateHall = true; clearHallTimer()" 
             @mouseleave="startHallTimer()">
          <button class="nav-btn create-hall-btn" 
                  :class="{ 'active': activeNav === 'create-hall' }"
                  @click="setActiveNav('create-hall')">
            创作大厅
            <i class="fa fa-chevron-down ml-1" :class="{ 'rotate-180': showCreateHall }"></i>
          </button>
          <!-- 创作大厅下拉内容 -->
          <div class="nav-dropdown-content" v-show="showCreateHall" :class="{ visible: showCreateHall }">
            <a @click="navigateTo('/compose'); setActiveNav('create-hall')" class="dropdown-item">
              <i class="fa fa-music mr-2"></i> AI作曲
            </a>
            <a @click="navigateTo('/lyrics'); setActiveNav('create-hall')" class="dropdown-item">
              <i class="fa fa-pencil mr-2"></i> 歌词生成
            </a>
            <a @click="navigateTo('/arrange'); setActiveNav('create-hall')" class="dropdown-item">
              <i class="fa fa-sliders mr-2"></i> 音乐改编
            </a>
            <a @click="navigateTo('/works'); setActiveNav('create-hall')" class="dropdown-item">
              <i class="fa fa-folder-open mr-2"></i> 作品管理
            </a>
          </div>
        </div>

        <!-- 音乐故事 -->
        <button class="nav-btn" 
                :class="{ 'active': activeNav === 'music-story' }"
                @click="navigateTo('/music-story'); setActiveNav('music-story')">
          音乐故事
        </button>

        <!-- 灵感社区 -->
        <button class="nav-btn" 
                :class="{ 'active': activeNav === 'inspiration-community' }"
                @click="navigateTo('/chat-interface'); setActiveNav('chat-interface')">
          灵感社区
        </button>
      </div>

      <!-- 用户信息+主题切换（公共部分） -->
      <div class="user-info" 
           @mouseenter="showUserMenu = true; clearUserTimer()" 
           @mouseleave="startUserTimer()">
        <!-- 主题切换按钮（单个） -->
        <button class="theme-toggle-btn" @click="toggleTheme" title="切换主题">
          <i :class="currentTheme === 'theme-dark' ? 'fa fa-sun-o' : 'fa fa-moon-o'"></i>
        </button>

        <!-- 会员标识 -->
        <div v-if="userInfo.isVip" class="vip-badge" title="高级会员">
          <i class="fa fa-diamond"></i>
        </div>

        <!-- 头像区域 -->
        <div class="avatar-wrapper" 
             @mouseenter="showUserMenu = true"
             @mouseleave="startUserTimer()">
          <img :src="isAvatarLoading ? defaultAvatar : userAvatar" 
               alt="用户头像" 
               class="avatar"
               @load="isAvatarLoading = false" 
               @error="handleAvatarError">
          <!-- 头像加载中占位 -->
          <div v-if="isAvatarLoading" class="avatar-loading">
            <div class="mini-spinner"></div>
          </div>
        </div>

        <span class="username">{{ userName }}</span>

        <!-- 用户下拉菜单 -->
        <div class="user-dropdown" 
             v-show="showUserMenu"
             :class="{ visible: showUserMenu }"
             @mouseenter="showUserMenu = true; clearUserTimer()"
             @mouseleave="startUserTimer()">
          <a @click="navigateToProfile" class="dropdown-item">
            <i class="fa fa-user-o"></i> 个人中心
          </a>
          <a @click="navigateToSettings" class="dropdown-item">
            <i class="fa fa-cog"></i> 账户设置
          </a>
          <div class="dropdown-divider"></div>
          <a @click="handleLogout" class="dropdown-item logout-item">
            <i class="fa fa-sign-out"></i> 退出登录
          </a>
        </div>
      </div>
    </nav>

    <!-- 页面内容插槽 -->
    <main class="page-content">
      <slot></slot>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <div class="footer-content">
        <p>&copy; 2025 MelodyAI - 释放AI的音乐创造力</p>
        <div class="footer-links">
          <a @click="openExternalLink('https://www.bilibili.com/video/BV1LvaHzDEhL?t=62.6')">帮助中心</a>
          <a @click="openExternalLink('https://www.bilibili.com/video/BV1LvaHzDEhL?t=62.6')">关于我们</a>
          <a @click="openExternalLink('https://www.bilibili.com/video/BV1LvaHzDEhL?t=62.6')">隐私政策</a>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';

// 路由实例
const router = useRouter();
const route = useRoute();

// 公共状态
const currentTheme = ref(localStorage.getItem('appTheme') || 'theme-dark');
const activeNav = ref('create-hall');
const showCreateHall = ref(false);
const hallTimer = ref(null);
const showUserMenu = ref(false);
const userTimer = ref(null);

// 用户信息
const userInfo = ref({
  name: '',
  username: '',
  userId: '',
  id: '',
  isVip: localStorage.getItem('userVip') === 'true',
  worksCount: Number(localStorage.getItem('userWorksCount')) || 0
});
const userAvatar = ref('');
const defaultAvatar = 'https://picsum.photos/id/64/200';
const isAvatarLoading = ref(true);

// 计算属性：用户名显示
const userName = computed(() => {
  return userInfo.value.name || userInfo.value.username || '亲爱的音乐创作者';
});

// 初始化用户头像
const initUserAvatar = () => {
  const storedUser = localStorage.getItem('currentUser');
  if (storedUser) {
    const user = JSON.parse(storedUser);
    userInfo.value = { ...userInfo.value, ...user };
  }
  const userId = Number(userInfo.value.userId || userInfo.value.id || 64);
  userAvatar.value = `https://picsum.photos/id/${isNaN(userId) ? 64 : userId}/200`;
};
initUserAvatar();

// 导航选中状态设置
const setActiveNav = (navItem) => {
  activeNav.value = navItem;
  showCreateHall.value = false;
};

// 主题切换
const toggleTheme = () => {
  currentTheme.value = currentTheme.value === 'theme-dark' ? 'theme-fresh' : 'theme-dark';
  localStorage.setItem('appTheme', currentTheme.value);
};

// 创作大厅下拉菜单计时器
const startHallTimer = () => {
  clearHallTimer();
  hallTimer.value = setTimeout(() => {
    showCreateHall.value = false;
  }, 150);
};
const clearHallTimer = () => {
  if (hallTimer.value) {
    clearTimeout(hallTimer.value);
    hallTimer.value = null;
  }
};

// 用户下拉菜单计时器
const startUserTimer = () => {
  clearUserTimer();
  userTimer.value = setTimeout(() => {
    showUserMenu.value = false;
  }, 200);
};
const clearUserTimer = () => {
  if (userTimer.value) {
    clearTimeout(userTimer.value);
    userTimer.value = null;
  }
};

// 跳转到个人中心
const navigateToProfile = () => {
  navigateTo('/profile');
  showUserMenu.value = false;
};

// 跳转到账户设置
const navigateToSettings = () => {
  navigateTo('/accountsettings');
  showUserMenu.value = false;
};

// 导航跳转
const navigateTo = (path) => {
  router.push(path).catch(err => {
    console.error('导航失败：', err);
    alert('页面跳转失败，请刷新页面重试');
  });
};

// 退出登录
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    localStorage.removeItem('userToken');
    localStorage.removeItem('currentUser');
    localStorage.removeItem('userVip');
    localStorage.removeItem('userWorksCount');
    router.replace('/login');
  }
};

// 头像加载失败处理
const handleAvatarError = () => {
  userAvatar.value = defaultAvatar;
  isAvatarLoading.value = false;
};

// 外部链接打开
const openExternalLink = (url) => {
  try {
    window.open(url, '_blank');
  } catch (error) {
    console.error('打开外部链接失败：', error);
    alert(`无法打开链接，请手动访问: ${url}`);
  }
};

// 页面加载时初始化
onMounted(() => {
  activeNav.value = route.meta.navKey || 'create-hall';
  
  router.afterEach((to) => {
    if (to.meta.navKey) {
      activeNav.value = to.meta.navKey;
    }
  });

  document.addEventListener('click', (e) => {
    const userInfoEl = document.querySelector('.user-info');
    const navDropdownEl = document.querySelector('.nav-dropdown');
    
    if (userInfoEl && !userInfoEl.contains(e.target)) {
      showUserMenu.value = false;
      clearUserTimer();
    }
    if (navDropdownEl && !navDropdownEl.contains(e.target)) {
      showCreateHall.value = false;
      clearHallTimer();
    }
  });
});
</script>

<style scoped>
/* 主题变量 */
.theme-dark {
  --bg-primary: #0f172a;
  --bg-secondary: rgba(255, 255, 255, 0.05);
  --bg-hover: rgba(255, 255, 255, 0.07);
  --primary-color: #6366f1;
  --primary-hover: #818cf8;
  --border-color: rgba(255, 255, 255, 0.1);
  --text-primary: white;
  --text-secondary: #e2e8f0;
  --text-tertiary: #bbb;
  --vip-color: #f59e0b;
  --logout-color: #ff6b6b;
  --nav-active-bg: rgba(99, 102, 241, 0.2);
}
.theme-fresh {
  --bg-primary: #f8fafc;
  --bg-secondary: rgba(59, 130, 246, 0.08);
  --bg-hover: rgba(59, 130, 246, 0.1);
  --primary-color: #3b82f6;
  --primary-hover: #60a5fa;
  --border-color: rgba(59, 130, 246, 0.15);
  --text-primary: #1e293b;
  --text-secondary: #334155;
  --text-tertiary: #64748b;
  --vip-color: #f97316;
  --logout-color: #ef4444;
  --nav-active-bg: rgba(59, 130, 246, 0.15);
}

/* 布局容器 */
.layout-container {
  min-height: 100vh;
  background: var(--bg-primary);
  color: var(--text-primary);
  display: flex;
  flex-direction: column;
  overflow-x: hidden;
  transition: background 0.3s ease, color 0.3s ease;
}

/* 导航栏样式 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background: var(--bg-primary);
  backdrop-filter: blur(12px);
  border-bottom: 1px solid var(--border-color);
  z-index: 100;
  transition: background 0.3s ease, border-color 0.3s ease;
}
.brand {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.5rem;
  font-weight: bold;
  color: var(--primary-color);
  cursor: pointer;
  transition: transform 0.2s ease;
}
.brand:hover {
  transform: scale(1.03);
}
.brand i {
  font-size: 1.8rem;
}

/* 导航按钮区域 */
.nav-links {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}
.nav-btn {
  background: transparent;
  border: none;
  color: var(--text-secondary);
  font-size: 1rem;
  padding: 0.6rem 1.2rem;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}
.nav-btn:hover {
  background: var(--bg-secondary);
  color: var(--primary-color);
}
.nav-btn.active {
  background: var(--nav-active-bg);
  color: var(--primary-color);
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.create-hall-btn i {
  font-size: 0.7rem;
  transition: transform 0.3s ease;
}

/* 创作大厅下拉菜单 */
.nav-dropdown {
  position: relative;
}
.nav-dropdown-content {
  position: absolute;
  top: 100%;
  left: 0;
  min-width: 180px;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  z-index: 99;
  margin-top: 0.5rem;
  opacity: 0;
  transform: translateY(-5px);
  pointer-events: none;
  transition: all 0.3s ease;
}
.nav-dropdown-content.visible {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}
.dropdown-item {
  display: flex;
  align-items: center;
  padding: 0.8rem 1.2rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: background 0.3s ease;
  text-decoration: none;
}
.dropdown-item:hover {
  background: var(--bg-secondary);
  color: var(--primary-color);
}
.dropdown-item i {
  width: 18px;
  text-align: center;
}

/* 主题切换按钮 */
.theme-toggle-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  color: var(--primary-color);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 0.8rem;
}
.theme-toggle-btn:hover {
  background: var(--bg-hover);
  transform: rotate(30deg);
}

/* 用户信息区域 */
.user-info {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  position: relative;
  z-index: 999;
}
.vip-badge {
  color: var(--vip-color);
  font-size: 1.2rem;
  cursor: pointer;
  transition: transform 0.3s ease;
}
.vip-badge:hover {
  transform: scale(1.2) rotate(10deg);
}
.avatar-wrapper {
  position: relative;
  cursor: pointer;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid var(--primary-color);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.avatar:hover {
  transform: scale(1.1);
  box-shadow: 0 0 15px rgba(59, 130, 246, 0.3);
}
.avatar-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: var(--bg-primary);
  display: flex;
  align-items: center;
  justify-content: center;
}
.mini-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(59, 130, 246, 0.5);
  border-top: 2px solid var(--primary-color);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
.username {
  white-space: nowrap;
  color: var(--text-secondary);
  font-size: 0.95rem;
  transition: color 0.3s ease;
}
.username:hover {
  color: var(--primary-color);
}

/* 用户下拉菜单 */
.user-dropdown {
  position: absolute;
  top: 120%;
  right: 0;
  width: 160px;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  z-index: 9999;
  overflow: hidden;
  opacity: 0;
  transform: translateY(-5px);
  pointer-events: none;
  transition: all 0.2s ease;
}
.user-dropdown.visible {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}
.dropdown-divider {
  height: 1px;
  background: var(--border-color);
  margin: 0.2rem 0;
}
.logout-item {
  color: var(--logout-color);
}
.logout-item:hover {
  background: rgba(239, 68, 68, 0.1);
  color: var(--logout-color);
}

/* 页面内容区 */
.page-content {
  flex: 1;
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

/* 页脚样式 */
.footer {
  text-align: center;
  padding: 1.5rem 2rem;
  border-top: 1px solid var(--border-color);
  color: var(--text-tertiary);
  font-size: 0.9rem;
  margin-top: auto;
  background: var(--bg-primary);
  transition: background 0.3s ease, border-color 0.3s ease;
}
.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 0.8rem;
}
.footer-links {
  display: flex;
  justify-content: center;
  gap: 1.5rem;
}
.footer-links a {
  color: var(--text-tertiary);
  cursor: pointer;
  transition: color 0.3s ease;
}
.footer-links a:hover {
  color: var(--primary-color);
  text-decoration: underline;
}

/* 动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式优化 */
@media (max-width: 1024px) {
  .nav-btn {
    font-size: 0.9rem;
    padding: 0.5rem 1rem;
  }
}
@media (max-width: 768px) {
  .navbar {
    padding: 1rem;
  }
  .brand span {
    display: none;
  }
  .user-info .username {
    display: none;
  }
  .nav-links {
    gap: 0.3rem;
  }
  .nav-btn {
    font-size: 0.8rem;
    padding: 0.4rem 0.8rem;
  }
  .create-hall-btn span {
    display: none;
  }
  .user-dropdown {
    width: 140px;
  }
}
@media (max-width: 480px) {
  .theme-toggle-btn {
    width: 32px;
    height: 32px;
    font-size: 0.8rem;
  }
  .footer-links {
    gap: 1rem;
    flex-wrap: wrap;
  }
}
</style>
